﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Event;
using FromUtils;
using DevExpress.XtraTreeList.Nodes;
using DevExpress.XtraTreeList;
using DevExpress.XtraBars;
using Data;
using System.IO;
using DevExpress.XtraEditors;
using DevExpress.XtraTreeList.Columns;
using Git;

namespace RequestDirectory
{

    /// <summary>
    /// 目录树-界面
    /// </summary>
    public partial class RequserDirectory : UserControl
    {
        /// <summary>
        /// 目录树数据-双向绑定
        /// </summary>
        private RequserDirectoryNodeData rdNodeData = new RequserDirectoryNodeData();

        /// <summary>
        /// 当前node
        /// </summary>
        private TreeListNode currentNode;

        public RequserDirectory()
        {
            InitializeComponent();
            //注册全局目录树保存事件
            EventGlobal.EvRequestDirectorySaveList += new EventGlobal.DeRequestDirectorySaveList(SaveList);
            //注册全局目录树重新加载事件
            EventGlobal.EvRequestDirectoryReloadList += new EventGlobal.DeRequestDirectoryReloadList(Reload);
            Reload();
        }

        /// <summary>
        /// 重新加载
        /// </summary>
        private void Reload() {
            this.treeList1.DataSource = rdNodeData.NodeData;
            this.treeList1.RefreshDataSource();
            this.treeList1.ExpandAll();
            NodeIco.SetUpStateImage(this.treeList1);
        }

        /// <summary>
        /// 事件触发-保存列表
        /// </summary>
        private void SaveList()
        {
            RequserDirectoryDataControl.SetSave(this.treeList1);
        }


        /// <summary>
        /// 鼠标点击目录树-鼠标点击
        /// 1.显示右键菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeList1_MouseClick(object sender, MouseEventArgs e)
        {
            PopupMenuControl.FormMenuControl(
                sender, 
                e, 
                popupMenu_右键功能菜单,
                MousePosition, 
                ref currentNode);
        }

        /// <summary>
        /// 双击节点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeList1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            NodeOpen.NodeDoubleOpen(sender, e, ref currentNode);
        }

        /// <summary>
        /// 鼠标点击目录树-不能编辑
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeList1_ShowingEditor(object sender, CancelEventArgs e)
        {
            e.Cancel = true;
        }

        /// <summary>
        /// 菜单-添加文件夹
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem_文件夹_ItemClick(object sender, ItemClickEventArgs e)
        {
            RequserDirectoryDataControl.SetAppendNode(this.treeList1, this.currentNode, "filegroup");
        }

        /// <summary>
        /// 菜单-添加请求器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem_控制器_ItemClick(object sender, ItemClickEventArgs e)
        {
            RequserDirectoryDataControl.SetAppendNode(this.treeList1, this.currentNode, "file");

        }

        /// <summary>
        /// 删除节点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem_删除节点_ItemClick(object sender, ItemClickEventArgs e)
        {
            int opendnumber = (int)currentNode.GetValue("opendnumber");
            if (opendnumber > 0)
            {
                DialogResult dr = XtraMessageBox.Show(@"检测到此节点已经被打开" + opendnumber.ToString() + "次,请先关闭", "节点已被打开？", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            }
            else
            {
                if (currentNode.Nodes.Count > 0)
                {
                    DialogResult dr = XtraMessageBox.Show("检测到此节点含有多个子节点,删除将无法恢复!", "确定要删除吗？", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
                    if (dr == DialogResult.Cancel)
                    {
                        return;
                    }
                    else
                    {
                        List<TreeListNode> ltln = TreeListTool.GetTreelistAllNode(currentNode);
                        foreach (TreeListNode tn in ltln)
                        {
                            RequserDirectoryDataControl.SetDelete(this.treeList1, tn);
                            /*string stringtypef = (string)tn.GetValue("type");
                            string stringIDf = (string)tn.GetValue("ID");
                            if (stringtypef.Equals("file"))
                            {
                                string thisExeFile = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
                                string thisDirectory = thisExeFile + @"JSONData" + "\\JSONDataList\\" + stringIDf;
                                if (Directory.Exists(thisDirectory))
                                {
                                    DirectoryInfo di = new DirectoryInfo(thisDirectory);
                                    di.Delete(true);
                                }
                            }
                            else
                            {
                                this.treeList1.DeleteNode(currentNode);
                            }*/

                        }
                        this.treeList1.DeleteNode(currentNode);
                        return;
                    }
                }
                else
                {

                    DialogResult dr = XtraMessageBox.Show("请确定删除此节点!删除将无法恢复!", "确定要删除吗？", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
                    if (dr == DialogResult.Cancel)
                    {
                        return;
                    }
                    else
                    {
                        RequserDirectoryDataControl.SetDelete(this.treeList1, currentNode);
                        /*string stringtypef = (string)currentNode.GetValue("type");
                        string stringIDf = (string)currentNode.GetValue("ID");
                        if (stringtypef.Equals("file"))
                        {
                            string thisExeFile = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
                            string thisDirectory = thisExeFile + @"JSONData" + "\\JSONDataList\\" + stringIDf;
                            if (Directory.Exists(thisDirectory))
                            {
                                DirectoryInfo di = new DirectoryInfo(thisDirectory);
                                di.Delete(true);
                            }
                            this.treeList1.DeleteNode(currentNode);
                        }
                        else
                        {
                            this.treeList1.DeleteNode(currentNode);
                        }*/
                    }
                }
            }
            EventGlobal.SetRequestDirectorySaveList();

        }

        /// <summary>
        /// 复制节点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem_复制_ItemClick(object sender, ItemClickEventArgs e)
        {
            string stringtype = (string)currentNode.GetValue("type");
            if (stringtype.Equals("file"))
            {
                string guid = RequserDirectoryDataControl.SetCopy(this.treeList1, currentNode);
                RequestParameteDataSave.setCopy(currentNode.GetValue("ID").ToString(), guid);

            }
            if (stringtype.Equals("filegroup"))
            {
                DialogResult dr = XtraMessageBox.Show(@"文件夹节点不能复制", "节点不能复制？", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            }
        }

        /// <summary>
        /// 菜单事件-展开或关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem_展开关闭_ItemClick(object sender, ItemClickEventArgs e)
        {
            NodeOpen.NodeDoubleOpen(sender, e, ref currentNode);
        }

        /// <summary>
        /// 全部收起
        /// </summary>
        public void treeListNodeCollapseAll()
        {           
            this.treeList1.CollapseAll();
        }

        /// <summary>
        /// 修改节点名称
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem_修改名称_ItemClick(object sender, ItemClickEventArgs e)
        {
            int opendnumber = (int)currentNode.GetValue("opendnumber");
            if (opendnumber > 0)
            {
                DialogResult dr = XtraMessageBox.Show(@"检测到此节点已经被打开" + opendnumber.ToString() + "次,请先关闭", "节点已被打开？", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);

            }
            else
            {
                XtraForm xf = new XtraForm();
                RequserDirectoryModifyName.RequserDirectoryModifyName rdm = new RequserDirectoryModifyName.RequserDirectoryModifyName();
                rdm.EvNodeModifyName += new EventGlobal.DeNodeModifyName(NodeModifyName);
                rdm.Dock = DockStyle.Fill;
                xf.StartPosition = FormStartPosition.CenterParent;
                xf.Width = 135;
                xf.Height = 120;
                xf.FormBorderStyle = FormBorderStyle.FixedToolWindow;
                xf.MinimizeBox = false;
                xf.MaximizeBox = false;
                xf.CloseBox = false;
                xf.Text = "修改名称";
                xf.Controls.Add(rdm);
                xf.ShowIcon = false;
                xf.ShowDialog();
            }

        }

        /// <summary>
        /// 现在移动节点的父节点
        /// </summary>
        private TreeListNode DragDropNowParent = null;

        //父节点
        private int DragDropNowParentint = 0;

        /// <summary>
        /// 节点移动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeList1_DragDrop(object sender, DragEventArgs e)
        {
            //现在移动的节点
            TreeListNode tlis = (DevExpress.XtraTreeList.Nodes.TreeListNode)e.Data.GetData(typeof(DevExpress.XtraTreeList.Nodes.TreeListNode));

            //移动到节点
            TreeList currentTreeList = sender as DevExpress.XtraTreeList.TreeList;
            TreeListHitInfo info = currentTreeList.CalcHitInfo(currentTreeList.PointToClient(new Point(e.X, e.Y)));
            TreeListNode tn = info.Node;

            if (tn != null)
            {
                string stringtype = (string)tn.GetValue("type");
                if (stringtype.Equals("file"))
                {
                    if (tlis.ParentNode == null)
                    {
                        e.Effect = DragDropEffects.None;
                        return;
                    }
                    DragDropNowParent = tn.ParentNode;
                    TreeListNodes max = tlis.ParentNode.Nodes;
                    int i = 0;
                    foreach (TreeListNode min in max)
                    {
                        if (min.Equals(tlis))
                        {
                            break;
                        }
                        i++;
                    }
                    DragDropNowParentint = i;
                    //取消移动
                    //e.Effect = DragDropEffects.None;
                    return;
                }
            }
        }

        /// <summary>
        /// treeList1_DragDrop配合解决如果拖动到请求器上就还原节点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeList1_AfterDragNode(object sender, AfterDragNodeEventArgs e)
        {
            TreeList currentTreeList = sender as DevExpress.XtraTreeList.TreeList;
            if (DragDropNowParent != null)
            {
                if (e.Node.ParentNode.GetValue("ID") != DragDropNowParent.GetValue("ID"))
                {
                    e.Node.TreeList.MoveNode(e.Node, DragDropNowParent, true);
                    e.Node.TreeList.SetNodeIndex(e.Node, DragDropNowParentint);
                }
            }
            DragDropNowParent = null;

            RequserDirectoryDataOrderBy.NodeOrderBys(currentTreeList.Nodes);
            System.Threading.Thread oThread = new System.Threading.Thread(new System.Threading.ThreadStart(delegate
            {

                CallbackOrderBy();
            }));
            oThread.IsBackground = true;
            oThread.Start();
        }


        #region 排序

        private delegate void OrderByCallback();

        private void CallbackOrderBy()
        {
            System.Threading.Thread.Sleep(200);
            this.BeginInvoke(new OrderByCallback(CallbackOrderByCall));
        }

        private void CallbackOrderByCall()
        {
            List<TreeListNode> listnode = RequserDirectoryDataOrderBy.listorderby;
            List<RequserDirectoryData> listorderby = new List<RequserDirectoryData>();
            foreach (TreeListNode Nodee in listnode)
            {
                listorderby.Add(new RequserDirectoryData()
                {
                    ID = Nodee.GetValue("ID").ToString(),
                    key = Nodee.GetValue("key") != null ? Nodee.GetValue("key").ToString() : "",
                    type = Nodee.GetValue("type") != null ? Nodee.GetValue("type").ToString() : "",
                    ParentID = Nodee.GetValue("ParentID") != null ? Nodee.GetValue("ParentID").ToString() : "",
                    opendnumber = Nodee.GetValue("opendnumber") != null ? (int)Nodee.GetValue("opendnumber") : 0,
                });
            }
            rdNodeData.SetNodeData(listorderby);
            NodeIco.SetUpStateImage(this.treeList1); 
        }
        #endregion

        /// <summary>
        /// 修改名称回调
        /// </summary>
        /// <param name="name"></param>
        private void NodeModifyName(string name)
        {
            this.currentNode.SetValue("key", name);
            NodeIco.SetUpStateImage(this.treeList1);
            RequserDirectoryDataControl.SetSave(this.treeList1);
        }

        /// <summary>
        /// 相关节点的展开状态
        /// </summary>
        List<string> ExpanListID = new List<string>();

        /// <summary>
        /// 系统默认导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem_导出系统默认_ItemClick(object sender, ItemClickEventArgs e)
        {
            string stringtype = (string)currentNode.GetValue("type");

            FolderBrowserDialog folder = new FolderBrowserDialog();
            folder.Description = "选择所有文件存放目录";
            if (folder.ShowDialog() == DialogResult.OK)
            {
                string sPath = folder.SelectedPath;
                //MessageBox.Show(sPath);
                List<string[]> IDs = new List<string[]>();
                List<RequserDirectoryData> lrdd = new List<RequserDirectoryData>();
                if (stringtype.Equals("file"))
                {
                    string stringkey = (string)currentNode.GetValue("key");
                    string stringid = (string)currentNode.GetValue("ID");
                    RequserDirectoryData rdd = new RequserDirectoryData()
                    {
                        ID = stringid,
                        key = stringkey,
                        type = "file"
                    };
                    lrdd.Add(rdd);
                    IDs.Add(new string[] { stringid, stringkey });
                    RequestParameteDataSave.setExport(IDs, sPath, lrdd);
                }
                if (stringtype.Equals("filegroup"))
                {
                    if (currentNode.Nodes.Count > 0)
                    {
                        RequserDirectoryDataOrderBy.NodeOrderBys(currentNode.Nodes);
                        //导出当前节点
                        RequserDirectoryData rddp = new RequserDirectoryData()
                        {
                            key = currentNode.GetValue("key").ToString(),
                            ParentID = "",
                            ID = currentNode.GetValue("ID").ToString(),
                            type = currentNode.GetValue("type").ToString()
                        };
                        lrdd.Add(rddp);
                        IDs.Add(new string[] { currentNode.GetValue("ID").ToString(), currentNode.GetValue("key").ToString() });

                        //导出当前节点下的所有子节点
                        foreach (TreeListNode node in RequserDirectoryDataOrderBy.listorderby)
                        {
                            string stringid = node.GetValue("ID").ToString();
                            string stringkey = node.GetValue("key").ToString();
                            RequserDirectoryData rdd = new RequserDirectoryData()
                            {
                                key = node.GetValue("key").ToString(),
                                ParentID = node.GetValue("ParentID").ToString(),
                                ID = stringid,
                                type = node.GetValue("type").ToString()
                            };
                            lrdd.Add(rdd);
                            IDs.Add(new string[] { stringid, stringkey });
                        }
                        RequestParameteDataSave.setExport(IDs, sPath, lrdd);
                    }

                }
            }

        }

        /// <summary>
        /// 系统默认导入
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem_导入系统默认_ItemClick(object sender, ItemClickEventArgs e)
        {
            FolderBrowserDialog folder = new FolderBrowserDialog();
            folder.Description = "选择所有文件存放目录";
            if (folder.ShowDialog() == DialogResult.OK)
            {
                string sPath = folder.SelectedPath;
                string thisFile = sPath + @"\\Export.json";
                if (File.Exists(thisFile))
                {
                    List<RequserDirectoryData> treeldd = (List<RequserDirectoryData>)this.treeList1.DataSource;
                    List<RequserDirectoryData> lrdd = RequestParameteDataSave.getExport(sPath, thisFile, treeldd);
                    if (lrdd != null)
                    {
                        RequserDirectoryData frd = lrdd.Find(x => x.ParentID == "" || x.ParentID == null);
                        if (frd != null)
                        {
                            frd.ParentID = currentNode == null ? "" : currentNode.GetValue("ID").ToString();
                        }
                        foreach (RequserDirectoryData rdd in lrdd)
                        {
                            treeldd.Add(rdd);
                        }
                        this.treeList1.RefreshDataSource();
                        NodeIco.SetUpStateImage(this.treeList1);
                        RequserDirectoryDataControl.SetSave(this.treeList1);
                    }
                    else
                    {
                        DialogResult dr = XtraMessageBox.Show(@"没有可导入的文件或文件格式异常", "找不到文件！", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                    }
                }
                else
                {
                    DialogResult dr = XtraMessageBox.Show(@"没有可导入的文件或文件格式异常", "找不到文件！", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                }
            }
        }

        /// <summary>
        /// git pull
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem_pull_ItemClick(object sender, ItemClickEventArgs e)
        {
            git g = new git();
            g.gitpull();
            EventGlobal.SetRequestDirectoryReloadList();
        }

        /// <summary>
        /// git push
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem_push_ItemClick(object sender, ItemClickEventArgs e)
        {
            git g = new git();
            g.gitaddcommit();
            g.gitpush();
        }
    }

}
